package com.dm.cloud.auth.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import lombok.Builder;
import lombok.Data;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Md5Util {

    /**
     * 多层加密
     * @param source 原文
     * @param level 加密层级
     * @return
     */
    public static EncryOption encryptionByLevel(String source,int level){
        MD5 md5 = MD5.create();
        String encryChart = source;
        List<String> salts=new ArrayList<>();
        //多层加密生成salt
        for (int i = 0; i < level; i++) {
            String salt = IdUtil.fastUUID();
            encryChart=md5.digestHex(encryChart+salt, StandardCharsets.UTF_8);
            salts.add(salt);
        }
        return EncryOption.builder()
                .encryChart(encryChart)
                .salts(salts)
                .source(source)
                .build();
    }

    /**
     * 多层加密
     * @param source 原文
     * @param salts 加密盐列表
     * @return
     */
    public static EncryOption encryptionBySalts(String source,List<String> salts){
        MD5 md5 = MD5.create();
        String encryChart = source;
        for (String salt : salts) {
            encryChart=md5.digestHex(encryChart+salt, StandardCharsets.UTF_8);
        }
        return EncryOption.builder()
                .encryChart(encryChart)
                .salts(salts)
                .source(source)
                .build();
    }

    @Data
    @Builder
    public static class EncryOption{
        /**
         * 盐列表
         */
        private List<String> salts;

        /**
         * 加密结果
         */
        private String encryChart;

        /**
         * 原文
         */
        private String source;
    }

}
